package com.yicun.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.fragment.app.Fragment;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yicun.companyapplication.MainActivity;
import com.yicun.companyapplication.R;
import com.yicun.model.Area;
import com.yicun.model.City;
import com.yicun.model.Province;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class RegionSelectorFragment extends Fragment {
    private Spinner spinnerProvince, spinnerCity, spinnerDistrict;
    private Button btnSearch;
    private EditText etBusinessScope;

    private CheckBox cbShowFavoritesOnly;

    private List<Province> provinces = new ArrayList<>();
    private List<City> currentCities = new ArrayList<>();
    private List<Area> currentAreas = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_region_selector, container, false);

        spinnerProvince = view.findViewById(R.id.spinner_province);
        spinnerCity = view.findViewById(R.id.spinner_city);
        spinnerDistrict = view.findViewById(R.id.spinner_district);
        btnSearch = view.findViewById(R.id.btn_search);
        etBusinessScope=view.findViewById(R.id.et_business_scope);
        cbShowFavoritesOnly=view.findViewById(R.id.cb_show_favorites_only);
        loadRegionData();
        setupSpinners();
        setupSearchButton();

        return view;
    }

    private void loadRegionData() {
        try {
            InputStream is = getResources().openRawResource(R.raw.city);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            is.close();

            String json = sb.toString();
            Gson gson = new Gson();
            Type type = new TypeToken<List<Province>>(){}.getType();
            provinces = gson.fromJson(json, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setupSpinners() {
        // 省份
        List<String> provinceNames = new ArrayList<>();
        provinceNames.add("");
        for (Province province : provinces) {
            provinceNames.add(province.getName());
        }

        ArrayAdapter<String> provinceAdapter = new ArrayAdapter<>(
                requireContext(), android.R.layout.simple_spinner_item, provinceNames);
        provinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerProvince.setAdapter(provinceAdapter);

        // 城市
        spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position>0){
                    currentCities = provinces.get(position-1).getCity();
                }
                List<String> cityNames = new ArrayList<>();
                cityNames.add("");
                for (City city : currentCities) {
                    cityNames.add(city.getName());
                }
                ArrayAdapter<String> cityAdapter = new ArrayAdapter<>(
                        requireContext(), android.R.layout.simple_spinner_item, cityNames);
                cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerCity.setAdapter(cityAdapter);

                // 重置区县选择器
                spinnerDistrict.setAdapter(new ArrayAdapter<>(
                        requireContext(), android.R.layout.simple_spinner_item, new ArrayList<>()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // 区县
        spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (currentCities != null && position < currentCities.size()) {
                   if(position>0){
                       currentAreas = currentCities.get(position-1).getArea();
                   }
                    List<String> areaNames = new ArrayList<>();
                    areaNames.add("");
                    for (Area area : currentAreas) {
                        areaNames.add(area.getName());
                    }
                    ArrayAdapter<String> districtAdapter = new ArrayAdapter<>(
                            requireContext(), android.R.layout.simple_spinner_item, areaNames);
                    districtAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerDistrict.setAdapter(districtAdapter);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    private void setupSearchButton() {
        btnSearch.setOnClickListener(v -> {
            String province = spinnerProvince.getSelectedItem() != null ?
                    spinnerProvince.getSelectedItem().toString() : "";
            String city = spinnerCity.getSelectedItem() != null ?
                    spinnerCity.getSelectedItem().toString() : "";
            String district = spinnerDistrict.getSelectedItem() != null ?
                    spinnerDistrict.getSelectedItem().toString() : "";
            String  businessScope=etBusinessScope.getText().toString();
            Boolean onlyShowStar=cbShowFavoritesOnly.isChecked();
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).onRegionSelected(province, city, district,businessScope,onlyShowStar);
            }
        });
    }
}